<template>
  <table class="recommend_table" cellspacing="0">
    <thead>
      <tr>
        <th v-for="(title, tindex) in titles"
            :key="tindex"
            @click="sort(title.id)"
            :class="{ active: sortdown === title.id }">{{ title.tname }}
          <span class="arrow"
                :class="sortdown[title.id] > 0 ? 'asc' : 'dsc'"
          ></span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, rindex) in rows"
          :key="rindex"
          @click="select(row.id)"
          :class="{ active: selectType === row.id }"
      >
        <td v-for="(col, tindex) in titles" :key="tindex" >
          {{ row[col.id] }}
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script>

export default {
  name: 'SortTable',
  props: [
    'titles',
    'rows',
  ],
  data() {
    return {
      sortType: '',
      sortdown: '',
      selectType: '',
    };
  },
  methods: {
    sort(dsctype) {
      this.sortdown = dsctype;
      this.rows.sort(this.dsc(dsctype));
    },
    dsc(attr) {
      return (a, b) => {
        const r1 = a[attr];
        const r2 = b[attr];
        if (r1 > r2) {
          return -1;
        }
        if (r1 < r2) {
          return 1;
        }
        return 1;
      };
    },
    select(type) {
      this.selectType = type;
    },
  },
};
</script>

<style scoped>

</style>
